package com.srwl.mytx.widget;

import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.DialogInterface;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.domain.Contact;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.graphics.Color.RED;
import static android.graphics.Color.TRANSPARENT;

/**
 * Created by dahai2070 on 2018/4/20 0020.
 */

public class ConnectInfiniteDialog extends DialogFragment {
    private static final String TAG = "ConnectInfiniteDialog";
    private static final int MIN_CLICK_DELAY_TIME = 50;
    private static long lastClickTime;
    private static final String CONTACT_LIST = "contact_list";
    private static final String CONNECT_KEY = "contact_key";
    private int itemWidth = 124;
    private int itemHeight = 57;
    // private ScaleView hvScrollView;
    private HVScrollView hvScrollView;
    // private MyScrollView containerView;
    private MyRelativeLayout containerView;
    private View progressBar;
    private ChildItemColumnRecord mStack;
    private String connectKey;
    private List<Contact> contactList;
    private int oldBaseLineY = 0;
    //垂直方向的间距
    private int verticalSpacing = 0;
    //水平方向的间距,也是连接线条的宽度
    private int horizontalSpacing = 0;
    //记录所有item的索引
    private int itemIndex = -1;
    private int heightPixels;
    //状态栏高度
    int statusHeight;
    private int totalChildItem;
    private int newBaseLineY;
    //最上端的item的左上顶点Y坐标
    private int minLeftTopY;
    //最下端的item的左下顶点Y坐标
    private int maxLeftTopY;


    public static ConnectInfiniteDialog getInstance(ArrayList<Contact> contactList, String connectKey) {
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(CONTACT_LIST, contactList);
        bundle.putString(CONNECT_KEY, connectKey);
        ConnectInfiniteDialog connectInfiniteDialog = new ConnectInfiniteDialog();
        connectInfiniteDialog.setArguments(bundle);
        return connectInfiniteDialog;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        contactList = getArguments().getParcelableArrayList(CONTACT_LIST);
        connectKey = getArguments().getString(CONNECT_KEY);
        mStack = new ChildItemColumnRecord();
        View view = inflater.inflate(R.layout.connect_infinite_dialog_view, container, false);
        hvScrollView = view.findViewById(R.id.hvScrollView);
        hvScrollView.setOnLongClickListener(initHVScrollViewLongClickListener());
        // hvScrollView = view.findViewById(R.id.scale_view);
        // hvScrollView.setStatusHeight(getActivity());
        containerView = view.findViewById(R.id.rl_container);
        progressBar = view.findViewById(R.id.progressBar2);
        //  containerView = view.findViewById(R.id.scroll_view);
        //  containerView.setOnLongClickListener(initHVScrollViewLongClickListener());
        Window window = getDialog().getWindow();

        window.setBackgroundDrawableResource(R.color.transparent);
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams attributes = window.getAttributes();
        // attributes.dimAmount = 0.0f;
        attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
        attributes.height = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(attributes);
        WindowManager wm = getActivity().getWindowManager();
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        float density = displayMetrics.density;
        heightPixels = displayMetrics.heightPixels;
        itemHeight = (int) (itemHeight * density);
        itemWidth = (int) (itemWidth * density);
        verticalSpacing = itemHeight * 2 / 3;
        horizontalSpacing = itemWidth / 2;
        // addItem((heightPixels - itemHeight) / 2, 50, 50, 1, contactList, "1");
        List<Map<String, Integer>> rectList = new ArrayList<>();
        Map<String, Integer> rectMap = new HashMap<>();
        Rect rect = new Rect();
        getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        statusHeight = rect.top;
        rectMap.put("rect_left_top_y", (heightPixels - itemHeight - statusHeight) / 2);
        rectMap.put("rect_left_top_x", horizontalSpacing / 2);
        rectList.add(rectMap);
        Contact contact = new Contact();
        contact.setChildContactList(contactList);
        ConnectInfiniteView infiniteView = new ConnectInfiniteView(getContext(), contact);
        infiniteView.setBaseLineY(heightPixels / 2);
        addItem(infiniteView, rectList);

        return view;
    }

    private HVScrollView.MyListener initHVScrollViewLongClickListener() {
        HVScrollView.MyListener myListener = new HVScrollView.MyListener() {

            @Override
            public void onLongClickEnd(View parentView, View dragView) {
                //进行数据交换
                if (parentView instanceof ConnectInfiniteView && dragView instanceof ConnectInfiniteView) {
                    ConnectInfiniteView dragInfiniteView = (ConnectInfiniteView) dragView;
                    ConnectInfiniteView newParentInfiniteView = (ConnectInfiniteView) parentView;
                    //判断newParentInfiniteView是否已经就是自己的父项
                    if (newParentInfiniteView == dragInfiniteView.getParentInfiniteView()) {
                        return;
                    }
                    //判断父项(newParentInfiniteView)是否是自己的子项或者子孙项,如果是，显示红色背景 提示用户，不能把自己添加到自己的子项
                    Contact childContact = dragInfiniteView.getContact();
                    Contact newParentContact = newParentInfiniteView.getContact();
                    if (isMyChildItem(childContact, newParentContact)) {
                        newParentInfiniteView.setBackgroundResource(R.drawable.connec_infinite_view_nomal_background);
                        //背景金变色动画，红色到透明
                        ValueAnimator colorAnim = ObjectAnimator.ofInt(newParentInfiniteView, "backgroundColor", RED, TRANSPARENT);
                        colorAnim.setDuration(1000);
                        colorAnim.setEvaluator(new ArgbEvaluator());
                        colorAnim.setRepeatCount(2);
                        colorAnim.setRepeatMode(ValueAnimator.REVERSE);
                        colorAnim.start();
                        // newParentInfiniteView.setBackgroundResource(R.drawable.connec_infinite_view_error_background);
                        return;
                    }


                    ConnectInfiniteView oldParentInfiniteView = dragInfiniteView.getParentInfiniteView();
                    Contact oldParentContact = oldParentInfiniteView.getContact();
                    //干掉自己
                    removeMySelf(dragInfiniteView);
                    //从旧父项中把自己删除
                    oldParentContact.getChildContactList().remove(childContact);


                    //如果旧父项中已经没有子项，那标记它的为折叠状态
                    if (oldParentInfiniteView.getConnectInfiniteViewList().size() == 0) {
                        oldParentInfiniteView.setSpreadChildItem(false);
                        oldParentContact.setHaveMoreChildContact(false);
                    }
//                    //重新设置自己的父项
//                    dragInfiniteView.setParentInfiniteView(newParentInfiniteView);
//                    //把自己添加到新父项的子项中
//                    newParentInfiniteView.addChildConnectInfiniteView(dragInfiniteView);
                    //重新设置dragInfiniteView的层级
                    childContact.getInfiniteConnects().get(0).setLayer(newParentInfiniteView.getLayer() + 1);
                    if (newParentContact.getChildContactList() == null) {
                        ArrayList<Contact> contacts = new ArrayList<>();
                        contacts.add(childContact);
                        newParentContact.setChildContactList(contacts);
                    } else {
                        newParentContact.getChildContactList().add(childContact);
                    }
                    newParentContact.setHaveMoreChildContact(true);
                    //如果新父项已经展开子项，先折叠子项
                    if (newParentInfiniteView.isSpreadChildItem()) {
                        removeChildItem(newParentInfiniteView);
                    }

                    //根据新父项的层级，设置dragView里面Contact中的层级

                    //让新父项展开子项
                    addChildItem(newParentInfiniteView);
// TODO: 2018/5/6 0006  连接服务器，更新联系人表中的联系人关系
                    //
                    String uId = newParentContact.getUser().getUId();
                    progressBar.setVisibility(View.VISIBLE);
                    Contact updateContact = new Contact();
                    updateContact.setcId(childContact.getCId());
                    updateContact.setmId(uId);
                    //    updateContact.settCid(childContact.gettCid());
                    JSONObject body = new JSONObject();
                    body.put("token", UserProfileManager.getInstance().getLoginUserInfo().getToken());
                    body.put("ct", updateContact);
                    RetrofitManager.getInstance().createRequest(UserService.class)
                            .refreshConnectInfinite(body)
                            .enqueue(new Callback<CommonResult>() {
                                @Override
                                public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                                    progressBar.setVisibility(View.GONE);

                                    CommonResult result = response.body();
                                    if (!response.isSuccessful() || result == null) {
                                        Log.e(TAG, "onResponse: " + response.message());
                                        showToast(getString(R.string.system_busy));
                                        return;
                                    }
                                    if (result.isError()) {
                                        Log.e(TAG, "onResponse: " + result.getMsg());
                                        switch (result.getStatus()) {
                                            case Constant.TOKEN_INVALID:
                                                showToast(getString(R.string.login_expire));
                                                break;
                                            case Constant.NO_AUTHORITY:
                                                showToast(getString(R.string.no_authority));
                                                break;
                                        }
                                        return;
                                    }

                                    showToast(getString(R.string.update_complete));
                                }

                                @Override
                                public void onFailure(Call<CommonResult> call, Throwable t) {
                                    progressBar.setVisibility(View.GONE);
                                    showToast(getString(R.string.system_busy));
                                }
                            });

                }

            }

            @Override
            public void onDragInTargetItem(View view) {
                if (view instanceof ConnectInfiniteView) {
                    view.setBackgroundResource(R.drawable.connec_infinite_view_focus_background);
                }
            }

            @Override
            public void onDragOutTargetItem(View view) {
                if (view instanceof ConnectInfiniteView) {
                    view.setBackgroundResource(R.drawable.connec_infinite_view_nomal_background);
                }
            }

            @Override
            public void onScale(float scale) {


            }
        };

        return myListener;
    }

    private boolean isMyChildItem(Contact dragInfiniteView, Contact newParentInfiniteView) {
        if (dragInfiniteView.getChildContactList() != null && dragInfiniteView.getChildContactList().size() != 0) {
            for (Contact contact : dragInfiniteView.getChildContactList()) {
                if (isMyChildItem(contact, newParentInfiniteView)) {
                    return true;
                }
                if (contact == newParentInfiniteView) {
                    return true;
                }
            }
        }

        return false;
    }

    public void addItem(ConnectInfiniteView infiniteView, List<Map<String, Integer>> rectList) {

        List<ConnectInfiniteView> views = addConnectInfiniteView(infiniteView, rectList);
        infiniteView.setConnectInfiniteViewList(views);
        mStack.addRecord(views.get(0).getLayer(), views);

        // mStack.recordView(recordKey, indexRecord);
    }

    public ConnectInfiniteView addParentConnectInfiniteView(ConnectInfiniteView childView, Map<String, Integer> rectMap, Contact parentContact) {

        LingLineView lingLineView = initLingLineView(rectMap);
        itemIndex++;
        ConnectInfiniteView parentView = getConnectInfiniteView(parentContact, rectMap);
        parentView.setLayer(childView.getLayer() - 1);
        //让ConnectInfiniteView 持久连接线，方便删除的时候，删除对应的连接线
        childView.setLingLineView(lingLineView);
        parentView.addChildConnectInfiniteView(childView);

        mStack.addRecord(parentView.getLayer(), parentView);
        return parentView;
    }

    public List<ConnectInfiniteView> addConnectInfiniteView(final ConnectInfiniteView parentInfiniteView, List<Map<String, Integer>> rectList) {
        List<ConnectInfiniteView> views = new ArrayList<>();
        //将要添加的item的左上顶点X坐标,同一列item的X坐标相同，左对齐
        // List<Map<String, Integer>> childItemRectList = parentInfiniteView.getChildItemRectList();
        List<Contact> childContactList = parentInfiniteView.getContact().getChildContactList();
        for (int i = 0; i < childContactList.size(); i++) {
            Map<String, Integer> rectMap = rectList.get(i);

            final Contact targetContact = childContactList.get(i);

            itemIndex++;
            //将要添加的item的左上顶点Y坐标

            ConnectInfiniteView childInfiniteView = getConnectInfiniteView(targetContact, rectMap);
            //==0 表示是添加第一个item，不画连接线
            if (itemIndex == 0) {
                childInfiniteView.setLayer(0);
            } else {
                childInfiniteView.setLayer(parentInfiniteView.getLayer() + 1);
                childInfiniteView.setParentInfiniteView(parentInfiniteView);
                LingLineView lingLineView = initLingLineView(rectMap);
                childInfiniteView.setLingLineView(lingLineView);
            }


            // containerView.addView(childInfiniteView, layoutParams);
            views.add(childInfiniteView);
            // oldBaseLineY = baseLineY;
        }

        return views;
    }

    public List<ConnectInfiniteView> addBrotherInfiniteView(final ConnectInfiniteView parentInfiniteView, ConnectInfiniteView clickInfiniteView, Contact brotherContact, List<Map<String, Integer>> rectList) {
        List<ConnectInfiniteView> views = new ArrayList<>();
        //将要添加的item的左上顶点X坐标,同一列item的X坐标相同，左对齐


        List<Contact> childContactList = parentInfiniteView.getContact().getChildContactList();
        for (int i = 0; i < childContactList.size(); i++) {
            Map<String, Integer> rectMap = rectList.get(i);
            //生成连接线
            LingLineView lingLineView = initLingLineView(rectMap);
            final Contact targetContact = childContactList.get(i);
            if (targetContact.getcId().equals(brotherContact.getcId())) {
                clickInfiniteView.setLingLineView(lingLineView);
                continue;
            }
            itemIndex++;

            ConnectInfiniteView childInfiniteView = getConnectInfiniteView(targetContact, rectMap);
            if (itemIndex == 0) {
                childInfiniteView.setLayer(0);
            } else {
                childInfiniteView.setLayer(parentInfiniteView.getLayer() + 1);
                childInfiniteView.setParentInfiniteView(parentInfiniteView);
            }

            // containerView.addView(childInfiniteView, layoutParams);
            childInfiniteView.setLingLineView(lingLineView);
            views.add(childInfiniteView);
            // oldBaseLineY = baseLineY;
        }

        return views;
    }

    @NonNull
    public ConnectInfiniteView getConnectInfiniteView(Contact targetContact, Map<String, Integer> rectMap) {
        ConnectInfiniteView childInfiniteView = new ConnectInfiniteView(getContext(), targetContact);
        childInfiniteView.init();
        childInfiniteView.setId(View.generateViewId());
        childInfiniteView.setTag(itemIndex);
        // connectInfiniteView.setId(View.generateViewId());

        // 定义及设置出场动画
        ScaleAnimation animation = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        // animation.setInterpolator(new BounceInterpolator());
        // animation.setStartOffset( 50);// 动画秒数。
        animation.setFillAfter(true);
        animation.setDuration(500);
        childInfiniteView.startAnimation(animation);

        childInfiniteView.setGetMoreContactClickListener(getListener(childInfiniteView));
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(itemWidth, itemHeight);
        int leftTopX = rectMap.get("rect_left_top_x");
        int leftTopY = rectMap.get("rect_left_top_y");
        layoutParams.topMargin = leftTopY;
        layoutParams.leftMargin = leftTopX;

        containerView.addView(childInfiniteView, layoutParams);
        return childInfiniteView;
    }

    @NonNull
    public View.OnClickListener getListener(final ConnectInfiniteView clickInfiniteView) {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //防止重复点击
                long curClickTime = System.currentTimeMillis();
                if ((curClickTime - lastClickTime) < MIN_CLICK_DELAY_TIME) {
                    //点击间隔时间小于设置的最短间隔时间，return
                    return;
                }
                lastClickTime = curClickTime;

                if (!clickInfiniteView.getContact().isHaveMoreChildContact()) {
                    showToast(getString(R.string.not_have_more_child_contact));
                    return;
                }

                if (clickInfiniteView.isSpreadChildItem()) {
                    //清除子项并恢复此父Contact 为未展开子项状态

                    removeChildItem(clickInfiniteView);
                    //判断此列中是否全部折叠了子项,以便确定是否要把视图往左边移动
//                    for (Contact contact : contactList) {
//                        if (contact.isSpreadChildItem()) {
//                            return;
//                        }
//                    }
                    if (mStack.getRecord(clickInfiniteView.getLayer() + 1) != null && mStack.getRecord(clickInfiniteView.getLayer() + 1).size() != 0) {
                        return;
                    }

                    // 向左边移动hv中的view
                    if (clickInfiniteView.getParentInfiniteView() != null) {
                        //hvScrollView.smoothScrollTo((int) (clickInfiniteView.getX() - itemWidth - horizontalSpacing * 3 / 2), parentInfiniteView.getBaseLineY());// parentInfiniteView.getBaseLineY() - heightPixels / 2 == -1 ? 0 : parentInfiniteView.getBaseLineY() - heightPixels / 2
                        scroll(clickInfiniteView.getParentInfiniteView().getChildItemsBottomY(), clickInfiniteView.getParentInfiniteView().getChildItemsTopY(), (int) (clickInfiniteView.getX() - itemWidth - horizontalSpacing * 3 / 2));
                    }
                    return;
                }
                //如果此父Contact 含有ChildContactList，就直接显示到页面上
                // if (targetContact.getChildContactList() != null && targetContact.getChildContactList().size() != 0) {
                if (clickInfiniteView.getContact().getChildContactList() != null && clickInfiniteView.getContact().getChildContactList().size() != 0) {
                    if (clickInfiniteView.getParentInfiniteView() != null) {
                        addChildItem(clickInfiniteView);
                    } else {
                        addParentItem(clickInfiniteView);

                    }
                } else {
                    //如果没有，就从服务端获取数据
                    getChildContactListFromService(clickInfiniteView);
                }
            }
        };
    }


    public void removeChildItem(ConnectInfiniteView connectInfiniteView) {
        mStack.removeRecord(connectInfiniteView.getLayer() + 1, connectInfiniteView.getConnectInfiniteViewList());

        //递归删除子项
        for (ConnectInfiniteView infiniteView : connectInfiniteView.getConnectInfiniteViewList()) {
            if (infiniteView.getConnectInfiniteViewList() != null && infiniteView.getConnectInfiniteViewList().size() > 0) {
                removeChildItem(infiniteView);
            }
            containerView.removeView(infiniteView.getLingLineView());
            itemIndex--;
            containerView.removeView(infiniteView);
            //用得着自动回收吗？
            infiniteView = null;
            //containerView.removeView(infiniteView);
            itemIndex--;
        }
        connectInfiniteView.getConnectInfiniteViewList().clear();
        connectInfiniteView.setSpreadChildItem(false);
    }

    public void removeMySelf(ConnectInfiniteView connectInfiniteView) {
        if (connectInfiniteView.isSpreadChildItem()) {
            removeChildItem(connectInfiniteView);
        }
        LingLineView LingLineView = connectInfiniteView.getLingLineView();
        containerView.removeView(LingLineView);
        itemIndex--;
        containerView.removeView(connectInfiniteView);
        itemIndex--;
        //把自己从父view 中删掉
        connectInfiniteView.getParentInfiniteView().getConnectInfiniteViewList().remove(connectInfiniteView);
//        for (ConnectInfiniteView infiniteView : connectInfiniteView.getParentInfiniteView().getConnectInfiniteViewList()) {
//            if (infiniteView == connectInfiniteView) {
//                connectInfiniteView.getParentInfiniteView().getConnectInfiniteViewList().remove(connectInfiniteView);
//                break;
//            }
//        }
    }

    /**
     * 添加父项
     *
     * @param clickInfiniteView
     */
    public void addParentItem(ConnectInfiniteView clickInfiniteView) {
        Contact parentContact = clickInfiniteView.getContact().getParentContact();

        if (parentContact == null) {
            return;
        }

        List<Contact> childContactList = parentContact.getChildContactList();
        int parentLeftX = (int) (clickInfiniteView.getX() + horizontalSpacing + itemWidth);
        int parentLeftY;
        //只有一个子item
        int itemCount = 1;
        int brotherItemsTopY = (int) clickInfiniteView.getY();
        int brotherItemsBottomY = brotherItemsTopY + itemCount * itemHeight + (itemCount - 1) * verticalSpacing;
        int baseX = (int) clickInfiniteView.getX();
        int baseY = brotherItemsBottomY - (brotherItemsBottomY - brotherItemsTopY) / 2;
        List<Map<String, Integer>> childItemRectList = new ArrayList<>();
        if (childContactList != null && childContactList.size() > 1) {
            //有多个子联系人（父项的子项，就是当前点击项的兄弟项）,计算出整个兄弟项的上下边界，每个兄弟项的位置
            itemCount = childContactList.size();
            brotherItemsTopY = (int) clickInfiniteView.getY();
            brotherItemsBottomY = brotherItemsTopY + itemCount * itemHeight + (itemCount - 1) * verticalSpacing;
            baseY = brotherItemsBottomY - (brotherItemsBottomY - brotherItemsTopY) / 2;
            for (int i = 0; i < itemCount; i++) {
                if (i == 0) {
                    //第一个item 已经存在，无需构造他的位置信息
                    continue;
                }

                //构造兄弟项连接线信息
                Map<String, Integer> rectMap = new HashMap<>();

                rectMap.put("line_start_x", baseX - horizontalSpacing);
                rectMap.put("line_start_y", baseY);
                rectMap.put("line_end_y", brotherItemsTopY + (itemHeight + verticalSpacing) * i + itemHeight / 2);
                rectMap.put("line_end_x", baseX);

                //构造兄弟项位置信息
                rectMap.put("rect_left_top_y", brotherItemsTopY + (itemHeight + verticalSpacing) * i);
                rectMap.put("rect_left_top_x", baseX);
                childItemRectList.add(rectMap);

            }

        }
        if (parentContact != null) {

            //构造点击item 和父item的连接线信息

            Map<String, Integer> rectMap = new HashMap<>();
            rectMap.put("line_start_x", baseX - horizontalSpacing);
            rectMap.put("line_start_y", baseY);
            rectMap.put("line_end_x", baseX);
            rectMap.put("line_end_y", brotherItemsTopY + itemHeight / 2);

            //构造父item的位置信息
            rectMap.put("rect_left_top_y", baseY - itemHeight / 2);
            rectMap.put("rect_left_top_x", baseX - itemWidth - horizontalSpacing);
            ConnectInfiniteView parentView = addParentConnectInfiniteView(clickInfiniteView, rectMap, parentContact);
            parentView.setChildItemsTopY(brotherItemsTopY);
            parentView.setChildItemsBottomY(brotherItemsBottomY);
            clickInfiniteView.setParentInfiniteView(parentView);
            if (childContactList == null && itemCount > 1) {

                List<ConnectInfiniteView> connectInfiniteViews = addBrotherInfiniteView(parentView, clickInfiniteView, clickInfiniteView.getContact(), childItemRectList);
                parentView.setConnectInfiniteViewList(connectInfiniteViews);
                parentView.setSpreadChildItem(true);
                mStack.addRecord(parentView.getLayer() - 1, connectInfiniteViews);
            }

            scroll(brotherItemsTopY, brotherItemsBottomY, baseX - itemWidth - horizontalSpacing);


        }
//当前点击项还有从数据库获取的子项没有展开
        List<Contact> childContactList1 = clickInfiniteView.getContact().getChildContactList();
        if (childContactList1 != null && clickInfiniteView.getConnectInfiniteViewList() != null && childContactList1.size() != clickInfiniteView.getConnectInfiniteViewList().size()) {
            ConnectInfiniteView existentChildInfiniteView = clickInfiniteView.getConnectInfiniteViewList().get(0);
            int count = childContactList1.size();
            brotherItemsTopY = clickInfiniteView.getChildItemsTopY();
            brotherItemsBottomY = brotherItemsTopY + count * itemHeight + (count - 1) * verticalSpacing;
            for (int i = 0; i < count; i++) {
                if (1 == 0) {
                    continue;
                }

                childItemRectList.clear();
                //构造兄弟项连接线信息
                Map<String, Integer> rectMap = new HashMap<>();

                rectMap.put("line_start_x", baseX - horizontalSpacing);
                rectMap.put("line_start_y", baseY);
                rectMap.put("line_end_y", brotherItemsTopY + (itemHeight + verticalSpacing) * i + itemHeight / 2);
                rectMap.put("line_end_x", baseX);

                //构造兄弟项位置信息
                rectMap.put("rect_left_top_y", brotherItemsTopY + (itemHeight + verticalSpacing) * i);
                rectMap.put("rect_left_top_x", baseX);
                childItemRectList.add(rectMap);

            }
            clickInfiniteView.setChildItemsTopY(brotherItemsTopY);
            clickInfiniteView.setChildItemsBottomY(brotherItemsBottomY);

            List<ConnectInfiniteView> connectInfiniteViews = addBrotherInfiniteView(clickInfiniteView, existentChildInfiniteView, existentChildInfiniteView.getContact(), childItemRectList);
            clickInfiniteView.setConnectInfiniteViewList(connectInfiniteViews);
            clickInfiniteView.setSpreadChildItem(true);
            mStack.addRecord(clickInfiniteView.getLayer() + 1, connectInfiniteViews);

        }

    }

    /**
     * 添加子项
     *
     * @param clickInfiniteView
     */
    public void addChildItem(ConnectInfiniteView clickInfiniteView) {

        // Contact currentClickContact = contactList.get(currentClickItemIndex);
        //子联系人总计列表
        // List<Contact> totalChildContactList = new ArrayList<>();

        //发送碰撞的item列表（需要移动位置的item 列表）

        //需要展开子项的父项索引列表
        List<ConnectInfiniteView> needSpradItemList = new ArrayList<>();
        //碰撞标记：将要添加的item列和已经添加的item列是否重叠，如果重叠，则需要清除掉，已经添加的，全部重新add
        boolean hasCollision = false;
        int currentClickItemLeftTopY = (int) clickInfiniteView.getY();//rectList.get(currentClickItemIndex).get("rect_left_top_y");
        int currentClickItemLeftTopX = (int) clickInfiniteView.getX(); //rectList.get(currentClickItemIndex).get("rect_left_top_x");
        newBaseLineY = currentClickItemLeftTopY + itemHeight / 2;

        int tempChildItemCount = clickInfiniteView.getContact().getChildContactList().size();

        //通过基本线的Y坐标，计算出每个子项竖列的上下边界
        //将要添加的子项竖列的所有（子项+间隔）的一半
        int tempHalfTotalChildItemHight = (tempChildItemCount * itemHeight + (tempChildItemCount - 1) * verticalSpacing) / 2;
        //将要添加的子项竖列上边界
        minLeftTopY = newBaseLineY - tempHalfTotalChildItemHight;
        //将要添加的子项竖列下边界
        maxLeftTopY = newBaseLineY + tempHalfTotalChildItemHight;
        // for (int i = 0; i < contactList.size(); i++) {
//        for (int i = 0; i < parentInfiniteView.getContactUserInfo().getChildContactList().size(); i++) {
//            //把当前点击的父项添加进需要绘制子项的列表
//            if (i == currentClickItemIndex) {
//                needSpradChildItemIndexList.add(i);
//                continue;
//            }
//            //  Contact contact = contactList.get(i);
//            ConnectInfiniteView infiniteView = parentInfiniteView.getConnectInfiniteViewList().get(i);
//            if (infiniteView.isSpreadChildItem()) {
//
//                // int existentMaxLeftTopY = contact.getChildItemColumnInfo().getChildItemsBottomY();
//                // int existentMinLeftTopY = contact.getChildItemColumnInfo().getChildItemsTopY();
//                int existentMaxLeftTopY = infiniteView.getChildItemsBottomY();
//                int existentMinLeftTopY = infiniteView.getChildItemsTopY();
//                //碰撞检测/重叠检测，没碰撞就跳过
//                if (tempMinLeftTopY >= existentMaxLeftTopY + verticalSpacing || existentMinLeftTopY >= tempMaxLeftTopY + verticalSpacing) {
//                    continue;
//                }
//                //当前遍历项的子项边缘与点击项的子项边缘碰撞，需要清除并且重新展开
//                hasCollision = true;
//                //removeChildItem(contact);
//                removeChildItem(infiniteView);
//                needSpradChildItemIndexList.add(i);
//            }
//        }
//        for (int i = 0; i < parentInfiniteView.getConnectInfiniteViewList().size(); i++) {
//            ConnectInfiniteView infiniteView = parentInfiniteView.getConnectInfiniteViewList().get(i);
//            if (infiniteView.isSpreadChildItem()) {
//
//                // int existentMaxLeftTopY = contact.getChildItemColumnInfo().getChildItemsBottomY();
//                // int existentMinLeftTopY = contact.getChildItemColumnInfo().getChildItemsTopY();
//                int existentMaxLeftTopY = infiniteView.getChildItemsBottomY();
//                int existentMinLeftTopY = infiniteView.getChildItemsTopY();
//                //碰撞检测/重叠检测，没碰撞就跳过
//                if (tempMinLeftTopY >= existentMaxLeftTopY + verticalSpacing || existentMinLeftTopY >= tempMaxLeftTopY + verticalSpacing) {
//                    continue;
//                }
//                //当前遍历项的子项边缘与点击项的子项边缘碰撞，需要清除并且重新展开
//                hasCollision = true;
//                //removeChildItem(contact);
//                removeChildItem(infiniteView);
//                //把需要展开子项的索引添加进索引记录列表
//                needSpradChildItemIndexList.add(i);
//                //把当前遍历项的子联系人添加进子联系人总计列表；
//                totalChildContactList.addAll(infiniteView.getContactUserInfo().getChildContactList());
//            }
//        }
//        int layer = 0;
//        for (InfiniteConnect infiniteConnect : clickInfiniteView.getContactUserInfo().getInfiniteConnects()) {
//            if (infiniteConnect.getConnectKey().equals(connectKey)) {
//                layer = infiniteConnect.getLayer() + 1;
//                break;
//            }
//        }
        totalChildItem = clickInfiniteView.getContact().getChildContactList().size();
        List<ConnectInfiniteView> record = mStack.getRecord(clickInfiniteView.getLayer() + 1);
        needSpradItemList.add(clickInfiniteView);
        if (record != null && record.size() != 0) {
            checkCollision(needSpradItemList, minLeftTopY, maxLeftTopY, record, newBaseLineY);
        }

        int tempLeftTopY = minLeftTopY;
//        for (Integer parentItemIndex : needSpradChildItemIndexList) {
//            // Contact contact = contactList.get(parentItemIndex);
//            // Contact contact = parentInfiniteView.getConnectInfiniteViewList().get(parentItemIndex).getContactUserInfo();
//            ConnectInfiniteView infiniteView;
//            if (parentInfiniteView.getConnectInfiniteViewList() != null) {
//                infiniteView = parentInfiniteView.getConnectInfiniteViewList().get(parentItemIndex);
//            } else {
//                infiniteView = clickInfiniteView;
//            }
//            int parentItemLeftTopY = (int) infiniteView.getY();
//            int parentItemLeftTopX = (int) infiniteView.getX();
//            List<Map<String, Integer>> newLinkLineList = new ArrayList<>();
//            List<Map<String, Integer>> childItemRectList = new ArrayList<>();
//            int currentChildItemLeftTopY = 0;
//            for (int i = 0; i < infiniteView.getContactUserInfo().getChildContactList().size(); i++) {
//                currentChildItemLeftTopY = tempLeftTopY + (itemHeight + verticalSpacing) * i;
//                //构造连接线信息
//                Map<String, Integer> lineItem = new HashMap<>();
//                lineItem.put("line_start_x", parentItemLeftTopX + itemWidth);
//                lineItem.put("line_start_y", parentItemLeftTopY + itemHeight / 2);
//                lineItem.put("line_end_y", currentChildItemLeftTopY + itemHeight / 2);
//                lineItem.put("line_end_x", parentItemLeftTopX + itemWidth + horizontalSpacing);
//                newLinkLineList.add(lineItem);
//                //构造子项位置信息
//                Map<String, Integer> rectMap = new HashMap<>();
//                rectMap.put("rect_left_top_y", currentChildItemLeftTopY);
//                rectMap.put("rect_left_top_x", parentItemLeftTopX + itemWidth + horizontalSpacing);
//                childItemRectList.add(rectMap);
//
//            }
//            infiniteView.setLingLineList(newLinkLineList);
//            infiniteView.setChildItemRectList(childItemRectList);
//            // contact.getChildItemColumnInfo().setLingLineList(newLinkLineList);
//            // contact.getChildItemColumnInfo().setChildItemRectList(childItemRectList);
//            tempLeftTopY = currentChildItemLeftTopY + (itemHeight + verticalSpacing);
//        }

        for (ConnectInfiniteView infiniteView : needSpradItemList) {
            int parentItemLeftTopY = (int) infiniteView.getY();
            int parentItemLeftTopX = (int) infiniteView.getX();
            List<Map<String, Integer>> childItemRectList = new ArrayList<>();
            int currentChildItemLeftTopY = 0;
            for (int i = 0; i < infiniteView.getContact().getChildContactList().size(); i++) {
                currentChildItemLeftTopY = tempLeftTopY + (itemHeight + verticalSpacing) * i;
                //构造连接线信息
                Map<String, Integer> rectMap = new HashMap<>();
                // Map<String, Integer> lineItem = new HashMap<>();
                rectMap.put("line_start_x", parentItemLeftTopX + itemWidth);
                rectMap.put("line_start_y", parentItemLeftTopY + itemHeight / 2);
                rectMap.put("line_end_y", currentChildItemLeftTopY + itemHeight / 2);
                rectMap.put("line_end_x", parentItemLeftTopX + itemWidth + horizontalSpacing);
                // newLinkLineList.add(lineItem);
                //构造子项位置信息
                rectMap.put("rect_left_top_y", currentChildItemLeftTopY);
                rectMap.put("rect_left_top_x", parentItemLeftTopX + itemWidth + horizontalSpacing);
                childItemRectList.add(rectMap);

            }

            // contact.getChildItemColumnInfo().setLingLineList(newLinkLineList);
            // contact.getChildItemColumnInfo().setChildItemRectList(childItemRectList);
            tempLeftTopY = currentChildItemLeftTopY + (itemHeight + verticalSpacing);

            //保存当前item的子项竖列的上下边界
            infiniteView.setChildItemsBottomY(maxLeftTopY);
            infiniteView.setChildItemsTopY(minLeftTopY);
            //添加子项
            addItem(infiniteView, childItemRectList);
            //设置当前遍历项的子项展开状态为True;
            infiniteView.setSpreadChildItem(true);
        }


        //同一层级下， 有碰撞，一次展开多个父项的子项
        //  if (hasCollision) {
//            for (Integer parentItemIndex : needSpradChildItemIndexList) {
//                // Contact parentContact = contactList.get(parentItemIndex);
//                ConnectInfiniteView infiniteView = parentInfiniteView.getConnectInfiniteViewList().get(parentItemIndex);
//                //保存当前父项的子项竖列的上下边界
//                infiniteView.setChildItemsBottomY(maxLeftTopY);
//                infiniteView.setChildItemsTopY(minLeftTopY);
//                //parentContact.getChildItemColumnInfo().setChildItemsBottomY(maxLeftTopY);
//                // parentContact.getChildItemColumnInfo().setChildItemsTopY(minLeftTopY);
//
//                addItem(infiniteView);
//                // parentContact.setSpreadChildItem(true);
//                infiniteView.setSpreadChildItem(true);
//            }

//        for (ConnectInfiniteView infiniteView : needSpradItemList) {
//            //保存当前item的子项竖列的上下边界
//            infiniteView.setChildItemsBottomY(maxLeftTopY);
//            infiniteView.setChildItemsTopY(minLeftTopY);
//            //添加子项
//            addItem(infiniteView);
//            //设置当前遍历项的子项展开状态为True;
//            infiniteView.setSpreadChildItem(true);
//        }
        // }
        //无碰撞，只展开当前click父项的子项
//        else {
//            //保存当前父项的子项竖列的上下边界
//            clickInfiniteView.setChildItemsBottomY(maxLeftTopY);
//            clickInfiniteView.setChildItemsTopY(minLeftTopY);
//            // currentClickContact.getChildItemColumnInfo().setChildItemsBottomY(maxLeftTopY);
//            // currentClickContact.getChildItemColumnInfo().setChildItemsTopY(minLeftTopY);
//            addItem(clickInfiniteView);
//            // currentClickContact.setSpreadChildItem(true);
//            clickInfiniteView.setSpreadChildItem(true);
//        }
        clickInfiniteView.setBaseLineY(newBaseLineY);

//        int verticalOffset = 0;
//
//        //下边界超出屏幕，上边界在屏幕内
//        if (maxLeftTopY > heightPixels - statusHeight && minLeftTopY > statusHeight) {
//            verticalOffset = maxLeftTopY - heightPixels + statusHeight;
//        }
//        //下边界在屏幕，上边界超出屏幕
//        else if (maxLeftTopY < heightPixels - statusHeight && minLeftTopY < -statusHeight) {
//            verticalOffset = minLeftTopY - statusHeight;
//        }
//
//        hvScrollView.smoothScrollTo(currentClickItemLeftTopX - horizontalSpacing / 2, verticalOffset);//newBaseLineY - heightPixels / 2 == -1 ? 0 : (newBaseLineY - heightPixels / 2)
        scroll(maxLeftTopY, minLeftTopY, currentClickItemLeftTopX - horizontalSpacing / 2);

    }

    /**
     * 碰撞检测
     *
     * @param needSpradItemList
     * @param tempTopBorder
     * @param tempBottomBorder
     * @param record
     * @return
     */
    public void checkCollision(List<ConnectInfiniteView> needSpradItemList, int tempTopBorder, float tempBottomBorder, List<ConnectInfiniteView> record, int clickItemTopY) {
        boolean hasCollision = false;
        for (int i = 0; i < record.size(); i++) {
            ConnectInfiniteView infiniteView = record.get(i);
            //已经存在的item上下边界
            int existentTopBorder = infiniteView.getParentInfiniteView().getChildItemsTopY();
            int existentBottomBorder = infiniteView.getParentInfiniteView().getChildItemsBottomY();
            //无碰撞情况
            if (tempTopBorder >= existentBottomBorder + verticalSpacing || existentTopBorder >= tempBottomBorder + verticalSpacing) {
                continue;
            }
            hasCollision = true;
            //该子项的父项已经添加进列表
//            if (!infiniteView.getParentInfiniteView().isSpreadChildItem()) {
//                record.remove(i);
//                continue;
//            }
            removeChildItem(infiniteView.getParentInfiniteView());
            //  record.remove(i);
            //发生碰撞，区分情况，以已经存在的item组（1）为固定参照，用将要添加的item组（2）的边界去比对，如果2的下方和1的上方发生碰撞，2高于1
            if (tempTopBorder < existentTopBorder && tempBottomBorder > existentTopBorder && tempBottomBorder < existentBottomBorder) {
                //因为2高于1，所以将该infiniteView，追加到列表后面，是为了让2的子项显示的位置高于1
                needSpradItemList.add(infiniteView.getParentInfiniteView());
            }//发生碰撞，以已经存在的item组（1）为固定参照，用将要添加的item组（2）的边界去比对，如果2的上方和1的下方发生碰撞，2低于1
            else if (tempTopBorder < existentBottomBorder && tempTopBorder > existentTopBorder && tempBottomBorder > existentBottomBorder) {
                //因为2低于1，所以将该infiniteView，插入到列表前面，是为了让1的子项显示的位置高于2
                needSpradItemList.add(0, infiniteView.getParentInfiniteView());
            }
            //包含关系，将要添加的包含已经存在的，或者是已经存在的包含将要添加的，
            // 这样子项的位置的先后顺序，以当前遍历项的父项Y方向位置与将要添加子项的item的Y方向位置做比较，y小的子项在上方，
            else {
                if (infiniteView.getParentInfiniteView().getY() < clickItemTopY) {
                    needSpradItemList.add(0, infiniteView.getParentInfiniteView());
                } else {
                    needSpradItemList.add(infiniteView.getParentInfiniteView());
                }
            }
            // collisionInfiniteViews.add(infiniteView);
            // totalChildContactList.addAll(infiniteView.getParentInfiniteView().getContactUserInfo().getChildContactList());
            totalChildItem += infiniteView.getParentInfiniteView().getContact().getChildContactList().size();
        }


        if (hasCollision) {
            //重新计算Y方向的基准线i
            int minY = 0;
            int maxY = 0;
            boolean bol_isFirstIn = true;
            for (ConnectInfiniteView infiniteView : needSpradItemList) {
                if (bol_isFirstIn) {
                    minY = (int) infiniteView.getY();
                    maxY = (int) infiniteView.getY();
                    bol_isFirstIn = false;
                }
                if (infiniteView.getY() < minY) {
                    minY = (int) infiniteView.getY();
                } else if (infiniteView.getY() > maxY) {
                    maxY = (int) infiniteView.getY();
                }
            }
            newBaseLineY = maxY - (maxY - minY) / 2 + itemHeight / 2;
            //重新计算基本线的Y坐标和子项竖列的上下边界
            //所有（子项+间隔）的一半
            int halfTotalChildItemHight = (totalChildItem * itemHeight + (totalChildItem - 1) * verticalSpacing) / 2;
            //最上端的item的左上顶点Y坐标
            minLeftTopY = newBaseLineY - halfTotalChildItemHight;
            //最下端的item的左下顶点Y坐标
            maxLeftTopY = newBaseLineY + halfTotalChildItemHight;
        }
        if (hasCollision) {
            checkCollision(needSpradItemList, minLeftTopY, maxLeftTopY, record, newBaseLineY);
        }
    }

    public void scroll(int maxLeftTopY, int minLeftTopY, int scrollX) {
        int verticalOffset = 0;
        //下边界超出屏幕，上边界在屏幕内
        if (maxLeftTopY > heightPixels - statusHeight && minLeftTopY > 0) {
            verticalOffset = maxLeftTopY - (heightPixels - statusHeight) + statusHeight;
        }
        //下边界在屏幕，上边界超出屏幕
        else if (maxLeftTopY < heightPixels - statusHeight && minLeftTopY < 0) {
            verticalOffset = minLeftTopY - statusHeight;
        }


        containerView.smoothScrollTo(scrollX, verticalOffset);
        hvScrollView.setScrollBorder(scrollX, verticalOffset);
        hvScrollView.smoothScrollTo(scrollX, verticalOffset);
    }

    /**
     * 添加连接线
     *
     * @param lineList
     */
    public List<LingLineView> addLine(List<Map<String, Integer>> lineList) {
        List<LingLineView> record = new ArrayList<>();
        for (Map<String, Integer> lineItem : lineList) {
            initLingLineView(lineItem);
            //  containerView.addView(view, params);

            // line入栈
            // mStack.push(view, tree_current);

        }
        return record;
    }

    public LingLineView initLingLineView(Map<String, Integer> lineItem) {
        itemIndex++;
        int startX = lineItem.get("line_start_x");
        int startY = lineItem.get("line_start_y");
        int endX = lineItem.get("line_end_x");
        int endY = lineItem.get("line_end_y");

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(horizontalSpacing, Math.abs(startY - endY) == 0 ? itemHeight : Math.abs(startY - endY));

        LingLineView view;
        if (startY > endY) {
            view = new LingLineView(getContext(), 0, startY - endY, endX - startX, 0, null);

            params.topMargin = endY;
        } else if (startY == endY) {
            view = new LingLineView(getContext(), 0, 50, endX - startX, 50, null);

            params.topMargin = endY - 50;
        } else {
            view = new LingLineView(getContext(), 0, 0, endX - startX, endY - startY, null);
            params.topMargin = startY;
        }
        params.leftMargin = startX;
        ScaleAnimation animation = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 1f,
                Animation.RELATIVE_TO_SELF, 0.0f);
        // animation.setInterpolator(new BounceInterpolator());
        // animation.setStartOffset( 50);// 动画秒数。
        animation.setFillAfter(true);
        animation.setDuration(550);
        view.setAnimation(animation);
        view.setTag(itemIndex);
        view.setId(View.generateViewId());
        // record.add(view);
        containerView.addView(view, params);
        return view;
    }


    public synchronized void getChildContactListFromService(final ConnectInfiniteView connectInfiniteView) {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(getContext(), getContext().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        final Contact targetContact = connectInfiniteView.getContact();
        Map<String, Object> info = new HashMap<>();
        final Contact contact = new Contact();
        contact.settId(targetContact.getTargetUser().getuId());
        info.put("contact", contact);
        info.put("connectKey", connectKey);
        JSONObject body = new JSONObject();
        body.put("token", UserProfileManager.getInstance().getLoginUserInfo().getToken());
        body.put("ct", info);
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .connectInfinite(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.TOKEN_INVALID:
                                    showToast(getString(R.string.login_expire));
                                    break;
                                case Constant.NOT_HAVE_MORE_CHILD_CONTACT:
                                    showToast(getString(R.string.not_have_more_child_contact));
                                    //  targetContact.setHaveMoreChildContact(false);
                                    connectInfiniteView.getContact().setHaveMoreChildContact(false);
                                    break;
                            }
                            return;
                        }
//                        LinkedTreeMap  map= (LinkedTreeMap) result.getData();
//                        Object contacts = map.get("contacts");
//                        Gson gson=new Gson();
//                        List<Contact> childContactList  = gson.fromJson(gson.toJson(contacts), new TypeToken<List<Contact>>() {}.getType());

                        JSONObject data = (JSONObject) result.getData();
                        List<Contact> childContactList = JSONObject.parseArray(data.getString("contacts"), Contact.class);


                        for (int i = 0; i < childContactList.size(); i++) {
                            Contact contact1 = childContactList.get(i);
//                            if (contact1.getIsParent() == 1) {
//                                targetContact.setParentContact(contact1);
//                                childContactList.remove(contact1);
//                                break;
//                            }
                        }

                        targetContact.setChildContactList(childContactList);
                        // connectInfiniteView.setChildContactList(childContactList);
                        connectInfiniteView.getContact().setChildContactList(childContactList);
                        // addItem(paly_y, paly_x, ppaly_x, tree_h, contacts, null);
                        //第一次点击，左右两边都展开
                        if (itemIndex == 0) {
                            addParentItem(connectInfiniteView);
                            addChildItem(connectInfiniteView);
                            return;
                        }
                        if (connectInfiniteView.getParentInfiniteView() != null) {
                            addChildItem(connectInfiniteView);
                        } else {
                            addParentItem(connectInfiniteView);
                        }

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        showToast(getString(R.string.system_busy));

                    }
                });

    }

    private void showToast(final String content) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), content, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        //退出对话框的时候清除子联系人
        if (contactList.get(0).getChildContactList() != null) {
            contactList.get(0).getChildContactList().clear();
        }
    }

    public class ChildItemColumnRecord {

        Map<Integer, List<ConnectInfiniteView>> itemTree = new HashMap<>();

        public void addRecord(Integer treeLayer, List<ConnectInfiniteView> recordList) {
            if (itemTree.containsKey(treeLayer)) {
                itemTree.get(treeLayer).addAll(recordList);
            } else {
                itemTree.put(treeLayer, recordList);
            }
        }

        public void addRecord(Integer treeLayer, ConnectInfiniteView view) {
            if (itemTree.containsKey(treeLayer)) {
                itemTree.get(treeLayer).add(view);
            } else {
                List<ConnectInfiniteView> recordList = new ArrayList<>();
                recordList.add(view);
                itemTree.put(treeLayer, recordList);
            }
        }

        public List<ConnectInfiniteView> getRecord(int treeLayer) {
            return itemTree.get(treeLayer);
        }

        List<ConnectInfiniteView> getAllRecord() {
            List<ConnectInfiniteView> views = new ArrayList<>();
            for (Integer integer : itemTree.keySet()) {
                views.addAll(itemTree.get(integer));
            }
            return views;
        }

        public void removeRecord(Integer key, List<ConnectInfiniteView> recordList) {
            if (itemTree.containsKey(key))
                itemTree.get(key).removeAll(recordList);
        }
    }
}
